import { analyzeResult } from '../../utils/CadAnalyzeUtil';
import { randomUUID } from '../../../../mapUtils/RandomUtil';

/**
 * 地块导入组件
 */
class ImportBlock {
  constructor(_) {
    this.tool = _;
    this.id = randomUUID();
    this.layeridPrefix = _.layeridPrefix;
    this.defaultYdlx = 'R1';
    this.option = {
      transSG: true,
      centerLng: '', //105
      coordinate: 'BJ', //BJ、CGCS2000
      charset: 'UTF-8'
    };
    this.init();
  }

  /**
   * 获取地图对象
   * @ignore
   */
  getMap() {
    return this.tool.getMap();
  }

  /**
   * 记录日志
   * @ignore
   */
  log() {
    return this.tool.log(...arguments);
  }

  /**
   * 选择文件
   * @param {Function} callback 回调事件
   */
  selectFile(callback) {
    let fileInput = document.createElement('input');
    fileInput.type = 'file';
    fileInput.style.display = 'none';
    fileInput.onchange = (e) => {
      this.cacheFile = e.target.files[0];
      callback(e);
    };
    document.body.appendChild(fileInput);
    fileInput.click();
  }

  /**
   * 上传已选择的文件
   * @param {Object} option 参数
   */
  async doUpload(option) {
    if (this.cacheFile) {
      return await this.uploadFile(this.cacheFile, option);
    }
    return {};
  }

  /**
   * 上传用户自己的文件
   * @param {File} file 文件
   * @param {Object} option 参数
   */
  async uploadFile(file, option) {
    if (option) {
      this.option = Object.assign({}, this.option, option);
    }
    let form = new FormData();
    form.append('file', file);
    this.log(this.option);
    form.centerLng = this.option.centerLng;
    form.coordinate = this.option.coordinate;
    form.charset = this.option.charset;
    form.transSG = this.option.transSG;
    let res = await this.tool.getApi().PwghGhsjQyfw.dxfYdxxController.post_dxfYdxxController_dxfFileUpload({
      params: form
    });
    if (!res.datas) {
      return;
    }
    let result = await analyzeResult(res.datas, this);
    this.totalFeatures = result.features;
    this.render();
    return result;
  }

  /**
   * 将图层数据转换成feature对象
   * @param {*} item 图层数据对象
   * @param {*} key 图层标识
   * @param {*} type 图层类型
   * @ignore
   */
  formatLayerFeature(item, key, type) {
    if (!item) {
      this.log(`数据为空：${type},${key}`);
      return null;
    }
    let sdoGtype = item.sdoGtype;
    let coordsList = item.coordsList;
    let feature = null;
    let color = this.tool.getBlockColor(this.defaultYdlx);
    switch (sdoGtype) {
      case 2001:
        feature = turf.point(coordsList[0]);
        feature.properties.color = color;
        feature.properties.size = 10;
        feature.properties.sourceType = 'Marker';
        feature.properties.label = item.text;
        break;
      case 2002:
        feature = turf.lineString(coordsList);
        feature.properties.color = color;
        feature.properties.width = 1;
        feature.properties.opacity = 1;
        feature.properties.sourceType = 'LineString';
        break;
      case 2003:
        if (coordsList.length === 3) {
          // 点数不足，尾部拼接第一个点
          coordsList.push(coordsList[0]);
        }
        if (coordsList.length >= 4) {
          // 首尾坐标不同，尾部拼接第一个点
          if (coordsList[0].join(',') !== coordsList[coordsList.length - 1].join(',')) {
            coordsList.push(coordsList[0]);
          }
          feature = turf.polygon([coordsList]);
          feature.properties = Object.assign({
            color: color,
            sourceType: 'Polygon'
          }, this.tool.defaultStyle);
        } else {
          feature = null;
          this.log('异常数据：', type, key, item);
        }
        break;
      default:
        break;
    }
    if (feature) {
      feature.properties.layer = key;
      // 设置图形ID
      feature.id = feature.properties.id = feature.properties.id || randomUUID();
    }
    return feature;
  }

  /**
   * 绘制导入地块
   */
  render() {
    this.visibleFeatures = this.totalFeatures;
    let featureCollection = turf.featureCollection(this.totalFeatures);
    this.getMap().getSource(this._SourceImportedId).setData(featureCollection);
    let polygon = turf.envelope(featureCollection);
    this.tool.getTool('BaseMapTool').fitBounds(turf.bbox(polygon));
  }

  /**
   * 切换图层显示状态
   * @param {Array} visibleLayers 显示图层
   */
  changeLayerVisible(visibleLayers) {
    let features = this.totalFeatures.filter((feature) => {
      return visibleLayers.indexOf(feature.properties.layer) >= 0;
    });
    this.visibleFeatures = features;
    this.getMap().getSource(this._SourceImportedId).setData(turf.featureCollection(features));
  }

  /**
   * 切换图层类型
   * @param {Array} layers 改变图层
   * @param {String} ydlx 用地类型
   */
  changeLayerType(layers, ydlx) {
    this.visibleFeatures.forEach((feature) => {
      if (layers.indexOf(feature.properties.layer) >= 0) {
        feature.properties.color = this.tool.getBlockColor(ydlx);
      }
    });
    this.getMap().getSource(this._SourceImportedId).setData(turf.featureCollection(this.visibleFeatures));
  }

  /**
   * 清除导入地块
   */
  clear() {
    this.getMap().getSource(this._SourceImportedId).setData(turf.featureCollection([]));
  }

  /**
   * 初始化
   * @ignore
   */
  init() {
    this.initId();
    this.initLayer();
  }

  /**
   * 初始化图层Id
   * @ignore
   */
  initId() {
    // 数据源
    this._SourceImportedId = this.layeridPrefix + '_source_imported_' + this.id;
    // 图层
    this._PolygonImportedLayerId = this.layeridPrefix + '_PolygonImported' + this.id;
    this._StrokeImportedLayerId = this.layeridPrefix + '_PolygonStrokeImported' + this.id;
  }

  /**
   * 初始化图层
   * @ignore
   */
  initLayer() {
    // 初始化数据源
    if(!this.tool.getMap().getSource(this._SourceImportedId)) {
      this.tool.getMap().addSource(this._SourceImportedId, {
        type: 'geojson',
        data: {
          type: 'FeatureCollection',
          features: []
        }
      });
    }
    // 初始化图层
    if(!this.tool.getMap().getLayer(this._PolygonImportedLayerId)) {
      this.tool.getMap().addLayer({
        id: this._PolygonImportedLayerId,
        type: 'fill',
        source: this._SourceImportedId,
        filter: ['all', ['==', '$type', 'Polygon']],
        paint: {
          'fill-color': ['get', 'color'],
          'fill-opacity': ['get', 'opacity']
        }
      });
    }
    if(!this.tool.getMap().getLayer(this._StrokeImportedLayerId)) {
      this.tool.getMap().addLayer({
        id: this._StrokeImportedLayerId,
        type: 'line',
        source: this._SourceImportedId,
        filter: ['all', ['==', '$type', 'Polygon']],
        paint: {
          'line-color': ['get', 'line-color'],
          'line-opacity': ['get', 'line-opacity'],
          'line-width': ['get', 'line-width']
        }
      });
    }
  }
}

export default ImportBlock;